<?php
// Change the line below into true for debugging of this part of the script
$debugPayson = false;

// Make connection and send the query
$gateways = new db;
$gateways->db_Select("e107shop_gateways", "*", "identifier='payson'");

// Read out the Payson Values from the Gateway table
while ($gatewayRow=$gateways->db_Fetch()) {
    $PS_AgentId     = $gatewayRow['account'];
    $PS_Url         = $gatewayRow['field1'];
    $PS_Key         = $gatewayRow['field2'];
    $PS_Email       = $gatewayRow['field5'];
    $PS_Guarantee   = $gatewayRow['field6'];
}

// Create a new order id
$orderid = e107shop_order_id();

// Some values needed to be able to calculate the MD5
$Cost = number_format($total, 2, ",", "");
$ExtraCost = 0;
$OkUrl = $shop_settings['path']."payson_verify.php";

// Calculate the MD5 (required by Payson)
$MD5string = $PS_Email . ":" . $Cost . ":" . $ExtraCost . ":" . $OkUrl . ":" . $PS_Guarantee . $PS_Key;
$MD5Hash = md5($MD5string);

// Build the form with the required parameters for Payson
$temp = "
<form action='".$PS_Url."' method='post'>
<input type='hidden' name='SellerEmail' value='".$PS_Email."' />
<input type='hidden' name='BuyerEmail' value='".$email."' />
<input type='hidden' name='Description' value='".$orderid."' />
<input type='hidden' name='Cost' value='".$Cost."' />
<input type='hidden' name='ExtraCost' value='0' />
<input type='hidden' name='OkURL' value='".$OkUrl."' />
<input type='hidden' name='CancelUrl' value='".$shop_settings['path']."payment_error.php' />
<input type='hidden' name='AgentID' value='".$PS_AgentId."' />
<input type='hidden' name='MD5' value='".$MD5Hash."' />
<input type='hidden' name='GuaranteeOffered' value='".$PS_Guarantee."' />
";

// build the payment button in the local language
$temp .= "<input type='image' src='".$shop_settings['path']."gateways/payson.gif' border='0' name='submit' alt='Payson' /></form>";

// Because we are gonna be redirected fromt he website we process the order before being redirected
e107shop_process_order($orderid, "pending", $cart_id, "payson", $region, $coupon);

// If debug is activated spill out the variables used in this script
if (ADMIN && $debugPayson) {
    $temp .= "
    <fieldset>
        <legend>Debug Information</legend>
        AgentId: ".$PS_AgentId."<br />
        Url: ".$PS_Url."<br />
        Key: ".$PS_Key."<br />
        Email: ".$PS_Email."<br />
        Guarantee: ".$PS_Guarantee."<br />
        Orderid: ".$orderid."<br />
        Cost: ".$Cost."<br />
        ExtraCost: ".$ExtraCost."<br />
        OkUrl: ".$OkUrl."<br />
        CancelUrl: ".$shop_settings['path']."payson_error.php<br />
        MD5String: ".$MD5string."<br />
        MD5Hash: ".$MD5Hash."<br />
        CustomerEmail: ".$email."<br />
        Shop Path: ".$shop_settings['path']."
    </fieldset>
    ";
}

// All is done, return the form to the originating calling script
return $temp;
